package com.buttonpay.home;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.buttonpay.DataHelper;
import com.buttonpay.ImageLoader;
import com.buttonpay.Products;
import com.buttonpay.R;
import com.buttonpay.favourite.SeparatedListAdapter;

public class Utilities extends Activity
{
	TextView tv_noroducts;
	ListView lvperatorList;
	Button btnBack,btnLogout;
	ArrayList<Products> electricityProducs=new ArrayList<Products>();
	ArrayList<Products> digitalTvProducts=new ArrayList<Products>();
	ArrayList<Products> dataTopUpProducts=new ArrayList<Products>();
	DataHelper datahelper;
	SeparatedListAdapter seprateListAdapter;
	DataHelper dh;
	public void onCreate(Bundle savedInstanceState) 
    {
		super.onCreate(savedInstanceState);
        setContentView(R.layout.utilitiies_layout);
        
          
         tv_noroducts=(TextView)findViewById(R.id.tvNoUilities);
        
         lvperatorList=(ListView)findViewById(R.id.lvOperatorList);
         
         datahelper=new DataHelper(this);
         
         System.out.println("----Getting Electricity Prodcts----");
         //electricity has system serivce ID 4.
         electricityProducs=datahelper.getProducts("4");
         
         System.out.println("----Getting Digital TV Products----");
         //Dgitv product has system servic id 8.
         digitalTvProducts=datahelper.getProducts("8");
         
         //data topup products has sys service id 16.
         System.out.println("----Getting DataTopUp Products----");
         dataTopUpProducts=datahelper.getProducts("16");
        
		 datahelper.close();
         btnBack=(Button)findViewById(R.id.btnPrevious);
         btnLogout=(Button)findViewById(R.id.btnLogout); 
         
         
         if(electricityProducs==null&&digitalTvProducts==null&&dataTopUpProducts==null)
         {
        	 tv_noroducts.setVisibility(TextView.VISIBLE);
         } 
         else
         {
        	 seprateListAdapter = new SeparatedListAdapter(this);
        	 if(electricityProducs!=null)
        	 {
        	 	 MyListAdapter electricityAdapter = new MyListAdapter(Utilities.this, electricityProducs,electricityProducs.get(0).getSystemServiceName());
        		 seprateListAdapter.addSection(electricityProducs.get(0).getSystemServiceName(), electricityAdapter);
        	 }
        	 if(digitalTvProducts!=null)
        	 {
        		 MyListAdapter digiTvAdapter=new MyListAdapter(Utilities.this, digitalTvProducts,digitalTvProducts.get(0).getSystemServiceName());
        		 seprateListAdapter.addSection(digitalTvProducts.get(0).getSystemServiceName(),digiTvAdapter);
        	 }
        	 if(dataTopUpProducts!=null)
        	 {
        		 MyListAdapter dataTopUpAdapter=new MyListAdapter(Utilities.this, dataTopUpProducts,dataTopUpProducts.get(0).getSystemServiceName());
                 seprateListAdapter.addSection(dataTopUpProducts.get(0).getSystemServiceName(), dataTopUpAdapter);	 
        	 }
        	 
     		 lvperatorList.setAdapter(seprateListAdapter);
     		 
         }
          
 		
 		btnBack.setOnClickListener(new OnClickListener()
 		{
 			
 			public void onClick(View arg0) 
 			{
 				// TODO Auto-generated method stub
 				finish();
 			}
 		});
 		
 		btnLogout.setOnClickListener(new OnClickListener()
		{
			
			public void onClick(View v) 
			{
				// TODO Auto-generated method stub
				new AlertDialog.Builder(Utilities.this)
		        .setTitle( "Exit Application" )
		        .setMessage( "Are you sure you want to Logout?" )
		        .setPositiveButton("YES", new android.content.DialogInterface.OnClickListener() 
		        {
		            public void onClick(DialogInterface arg0, int arg1) 
		            {
		                //do stuff onclick of YES
		            	setResult(2);
		            	finish();
		            }

					public void onClick(View v) 
					{
						// TODO Auto-generated method stub
						
					}
		        })
		        .setNegativeButton("NO",  new android.content.DialogInterface.OnClickListener() 
		        {
		            public void onClick(DialogInterface arg0, int arg1)
		            {
		                //do stuff onclick of CANCEL
		            	arg0.dismiss();
		               
		            }

					public void onClick(View v) 
					{
						// TODO Auto-generated method stub
					}
		        }).show();
				  		
			}
		});
 		
 		lvperatorList.setOnItemClickListener(new OnItemClickListener()
		{

			public void onItemClick(AdapterView<?> adapterView, View view, int position,
					long id) 
			{
				
				Products p=(Products)adapterView.getAdapter().getItem(position);
				System.out.println("Name:"+p.getProductName()+"\nBach ID:"+p.getBatchID()+"\n Product Type"+p.getProductType());
				
				TopUpDialog topUpDialog=new TopUpDialog(view.getContext(),p);
				topUpDialog.show();
//				TextView tvOperatorName=(TextView)view.findViewById(R.id.tvOperatorName);
//				UtilityDialog utilityDialog=new UtilityDialog(view.getContext(),tvOperatorName.getText().toString());
//				utilityDialog.show();
				 
			}
			
		});
 		  
    } 
	public static class ViewHolder
	 {
			public TextView tvOperatorName;
			public ImageView ivOperatorIcon;
			public ImageView ivAddToFavourite;
		 
    }
	
	 class MyListAdapter extends ArrayAdapter<Products> 
	 {
			
			ArrayList<Products> products;
			String sectionName;
			ImageLoader imageLoader;
			LayoutInflater vi ; 
			  
			
			public MyListAdapter(Context context, ArrayList<Products> products,String sectionName)
			{
				super(context, R.layout.row_lv_operator, products); 
				this.imageLoader=new ImageLoader(context);
				this.products=products;
				this.sectionName=sectionName;
				vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);	 
			}

			 

			public View getView(final int position, View convertView, ViewGroup parent) 
			{
				View v = convertView;
				ViewHolder holder = null;
				
				if (v == null) 
				{
						holder=new ViewHolder();  
						v = vi.inflate(R.layout.row_lv_operator, null); 
						holder.tvOperatorName=(TextView) v.findViewById(R.id.tvOperatorName);
						holder.ivOperatorIcon=(ImageView)v.findViewById(R.id.ivOperatorIcon);
						holder.ivAddToFavourite=(ImageView)v.findViewById(R.id.ivAddToFavourite);
						
						v.setTag(holder);
				}
				else
					holder=(ViewHolder)v.getTag();
				
					System.out.println("Product name:"+this.products.get(position).getProductName());
					System.out.println("Product Image Url:"+this.products.get(position).getImageURL());
					 
					holder.tvOperatorName.setText(this.products.get(position).getProductDesc());
					holder.ivOperatorIcon.setTag(this.products.get(position).getImageURL());
					imageLoader.DisplayImage(this.products.get(position).getImageURL(),Utilities.this,holder.ivOperatorIcon);
					
					//holder.ivOperatorIcon.setBackgroundResource(R.drawable.icon);
					
					if(isFav(products.get(position)))
					{
						holder.ivAddToFavourite.setBackgroundResource(R.drawable.favourite_marked);
						holder.ivAddToFavourite.setTag("marked");
					}
					else
					{
						holder.ivAddToFavourite.setBackgroundResource(R.drawable.favourite_unmarked);
						holder.ivAddToFavourite.setTag("unmarked");	
					}
					
			//		holder.tvOperatorName.setTag(sectionName);
			//		holder.ivOperatorIcon.setImageResource(this.products.get(position).getImageID());
				
					holder.ivAddToFavourite.setOnClickListener(new OnClickListener()
					{	 
						public void onClick(View view) 
						{
							if(view.getTag().toString().equalsIgnoreCase("unmarked"))
							{
								view.setTag("marked");
								view.setBackgroundResource(R.drawable.favourite_marked);
								//Toast.makeText(getApplicationContext(), values[position]+" Added in your Favourites!",Toast.LENGTH_SHORT).show();
							 
								addProductToFav(products.get(position));
							  	
							}
							else 
							{
								view.setTag("unmarked");
								view.setBackgroundResource(R.drawable.favourite_unmarked);
								
								//Toast.makeText(getApplicationContext(), values[position]+" Removed from your Favourite!",Toast.LENGTH_SHORT).show();
								
								deleteProductFromFav(products.get(position));
							}
						 
						}
					});
					return v; 
			}//getView 
			
			protected void deleteProductFromFav(Products p) 
			{
				try
				{
					 dh=new DataHelper(Utilities.this);
					 dh.deleteProdctFromFav(p.getProductID());
				}
				catch(Exception e)
				{
					e.printStackTrace();
				}
				finally
				{
					if(dh!=null)
					{
						dh.close();
					}
				}
				
			}
			void addProductToFav(Products p)
			{
			
				try
				{
					 dh=new DataHelper(Utilities.this);
					 dh.insert_topupFav(p.getSystemServiceID(),p.getSystemServiceName(),
							 			p.getProductID(), p.getProductName(),
							 			p.getProductDesc(), 
							 			p.getProductType(),
							 			p.getBatchID(),p.getminValue(),p.getMaxValue(),p.getImageURL());
				}
				catch(Exception e)
				{
					e.printStackTrace();
				}
				finally
				{
					if(dh!=null)
					{
						dh.close();
					}
				}
			}//AddProductToFavourite
			private boolean isFav(Products p)
			{
				try
				{
					 dh=new DataHelper(Utilities.this);
					 return dh.isProductInFav(p.getProductID(),p.getminValue(),p.getMaxValue());
				}
				catch(Exception e)
				{
					e.printStackTrace();
					return false;
				}
				finally
				{
					if(dh!=null)
					{
						dh.close();
					}
				}
				
			}
		}

//	public static class ViewHolder
//	 {
//			public TextView tvOperatorName;
//			public ImageView ivOperatorIcon; 
//		public ImageView ivAddToFavourite;
//     }
	
	 /*class MyListAdapter extends ArrayAdapter<String> 
	 {
			
			private final Context context;
			private final String[] values;
			private final Integer[] icons;
			LayoutInflater vi ;

			  
			
			public MyListAdapter(Context context, String[] values, Integer[] icons)
			{
				super(context, R.layout.row_lv_operator, values);
				this.context = context;
				this.values = values;
				this.icons=icons;
				 vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			}
 
			public View getView(final int position, View convertView, ViewGroup parent) 
			{
				View v = convertView;
				 ViewHolder holder = null;
				
				
				if (v == null) 
				{
						holder=new ViewHolder();  
						v = vi.inflate(R.layout.row_lv_operator, null); 
						holder.tvOperatorName=(TextView) v.findViewById(R.id.tvOperatorName);
						holder.ivOperatorIcon=(ImageView)v.findViewById(R.id.ivOperatorIcon);
						holder.ivAddToFavourite=(ImageView)v.findViewById(R.id.ivAddToFavourite);
						
						v.setTag(holder); 
					 
				}
				else
					holder=(ViewHolder)v.getTag();  
					holder.tvOperatorName.setText(values[position]);
					holder.ivOperatorIcon.setImageResource(icons[position]);
					
					
					if(AppData.UtilityfavouriteList.containsKey(values[position]))
					{
						holder.ivAddToFavourite.setBackgroundResource(R.drawable.favourite_marked);
						holder.ivAddToFavourite.setTag("marked");
					}
					else
					{
						holder.ivAddToFavourite.setBackgroundResource(R.drawable.favourite_unmarked);
						holder.ivAddToFavourite.setTag("unmarked");	
					}
					
					
					
					holder.ivAddToFavourite.setOnClickListener(new OnClickListener()
					{
						 
						public void onClick(View view) 
						{
							
							if(view.getTag().toString().equalsIgnoreCase("unmarked"))
							{
								view.setTag("marked");
								view.setBackgroundResource(R.drawable.favourite_marked);
								//Toast.makeText(getApplicationContext(), values[position]+" Added in your Favourites!",Toast.LENGTH_SHORT).show();
								AppData.UtilityfavouriteList.put(values[position],icons[position]);
								
								Set set = AppData.UtilityfavouriteList.entrySet(); 
								Iterator i = set.iterator(); 
								System.out.println("Addind item to Favourites.");
								
								while(i.hasNext()) 
								{ 
								
									Map.Entry me = (Map.Entry)i.next(); 
									System.out.print(me.getKey() + ": "); 
									System.out.println(me.getValue()); 
								} 	 
								
								
							}
							else 
							{
								view.setTag("unmarked");
								view.setBackgroundResource(R.drawable.favourite_unmarked);
								//Toast.makeText(getApplicationContext(), values[position]+" Removed from your Favourite!",Toast.LENGTH_SHORT).show();
								AppData.UtilityfavouriteList.remove(values[position]);


								Set set = AppData.UtilityfavouriteList.entrySet(); 
								Iterator i = set.iterator(); 
								System.out.println("Removing from Favourites");
								while(i.hasNext()) 
								{ 
									Map.Entry me = (Map.Entry)i.next(); 
									System.out.print(me.getKey() + ": "); 
									System.out.println(me.getValue()); 
								} 	
							}
						}
					}); 
	 
				 	return v; 
			}
		}	
*/}
